package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Created by 16060457 on 2018/1/2.
 */
public class AspectProxy implements Proxy {

    private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);

    /**
     * 执行链式代理
     *
     * @param proxyChain
     */
    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;
        
        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] methodParams = proxyChain.getMethodParams();
        
        begin();

        try {
            if (intercept(cls, method, methodParams)) {
                before(cls, method, methodParams);
                result = proxyChain.doProxyChain();
                after(cls, method, methodParams, result);
            } else {
                result = proxyChain.doProxyChain();
            }
        } catch (Exception e) {
            logger.error("proxy failure", e);
            error(cls, method, methodParams, e);
            throw e;
        } finally {
            end();
        }
        return result;
    }

    public void end() {
    }

    public void error(Class<?> cls, Method method, Object[] methodParams, Exception e) {
    }

    public void after(Class<?> cls, Method method, Object[] methodParams, Object result) {
    }

    public void before(Class<?> cls, Method method, Object[] methodParams) {
    }

    public boolean intercept(Class<?> cls, Method method, Object[] methodParams) throws Throwable{
        return true;
    }

    public void begin() {
    }
}
